<template>
  <view class="temporarySeal">
    <u-top-tips ref="uTips"></u-top-tips>
    <view v-if="isEnd === 'devLocked'" class="end">
      <view class="e1">{{$t('已结束用章')}}</view>
      <view class="e2">
        {{$t('已盖次数')}}
        <text class="e-text">{{ parms.num }}</text>
      </view>
      <view class="e-icon">
        <u-icon name="checkbox-mark" size="100"></u-icon>
      </view>
    </view>

    <view v-else class="top-text">
      <view class="num">{{ parms.num }}</view>
      <view class="num-text">{{$t('已盖次数')}}</view>
    </view>
    <view class="btn">
      <u-button v-if="isEnd === 'devLocked'" type="primary" @click="navigetback">{{$t('返回')}}</u-button>
      <u-button v-else :loading="end.loading" type="primary" @click="closingSeal">{{$t('结束盖章')}}</u-button>
    </view>
  </view>

</template>

<script>
import {mapGetters, mapMutations} from 'vuex'

export default {
  components: {},
  computed: mapGetters(["userInfo", 'api', 'Bluetooth']),
  data() {
    return {
      isEnd: '',
      parms: {//传过来的参数
        num: 0,//盖章次数
        total: 0,//总的拍照记录
      },
      end: {
        loading: false
      }
    };
  },
  onLoad(e) {
    uni.setNavigationBarTitle({title: this.$t('临时盖章')})

    //停止搜索蓝牙
    this.$lizhao.bluetooth.stopBluetoothDevicesDiscovery()
    this.$lizhao.bluetooth.initUserCount(0)
  },
  onReady() {
    this.$lizhao.bluetooth.initParams()
    this.dingSignet_idUse()
    //申请单推送和临时盖章的丢次错误处理
    uni.$off('BLEuserCountError')
    uni.$on('BLEuserCountError', (res) => {
      let list = []
      for (let i = res.userCount; i < res.count; i++) {
        list.push(i)
      }
      // this.$refs.uTips.show({
      //   title: '蓝牙波动导致第' + list + '次盖章导致界面次数不一致，请继续盖印',
      //   type: 'warning',
      //   duration: '3500'
      // })
    })
    //监听回复
    uni.$off('onBLECharacteristicValueChange')
    uni.$on('onBLECharacteristicValueChange', (res) => {
      uni.hideLoading()
      //console.log(res);
      if (res.cmd === 128 && res.data.topic === `/sys/e2263a5940a843e3b2f4d4c90a624835/${this.Bluetooth.device.sn}/thing/service/temporary_use_reply`) {
        uni.showToast({
          title: this.$t('已发送临时盖章'),
          icon: "none"
        });
      }
      if (res.cmd === 128 && res.data.topic === `/sys/e2263a5940a843e3b2f4d4c90a624835/${this.Bluetooth.device.sn}/thing/service/authorized_over_reply`) {
        uni.navigateBack({
          delta: 1
        });
        uni.closeBluetoothAdapter();
        setTimeout(() => {
          this.end.loading = false
          uni.showToast({
            title: this.$t('已结束用章'),
            icon: "none"
          });
        }, 500)
      }
      if (res.cmd === 128 && res.data.topic === `/sys/e2263a5940a843e3b2f4d4c90a624835/${this.Bluetooth.device.sn}/thing/event/punch/post`) {
        let {count, audit, total} = JSON.parse(res.data.payload).params
        if (audit === 1) {//审计
          this.parms.total = total
        } else if (audit === 0) {//非审计
          this.parms.num = count
        }
      }
      if (res.cmd === 130 && res.data) {
        if (res.data.event === 'devLocked' && this.end.loading === false) {//设备锁定
          this.isEnd = 'devLocked'
        }
      }
    })
  },
  onBackPress(options) {
    uni.closeBluetoothAdapter();
    if (options.from === 'navigateBack') {
      return false;
    }
    uni.navigateBack({
      delta: 1
    });
    return true;
  },
  methods: {
    navigetback() {
      uni.closeBluetoothAdapter();
      uni.navigateBack({
        delta: 1
      });
    },
    //临时盖章
    dingSignet_idUse() {
      uni.showLoading({
        title: this.$t('发送临时用印') + '..',
        mask: false
      });
      //发送物模型（临时用印）
      this.setObjectModel()
    },
    //发送物模型（临时用印）
    setObjectModel() {
      let payload = {
        id: "4806",
        method: "thing.service.temporary_use",
        params: {bizId: "", userId: this.userInfo.userId.toString()},
        "version": "1.0"
      }
      let body = {
        topic: "/sys/e2263a5940a843e3b2f4d4c90a624835/" + this.Bluetooth.device.sn + "/thing/service/temporary_use",
        payload: JSON.stringify(payload)
      }
      let length = this.$lizhao.scale.switch_sl(JSON.stringify(body).length, 16) // 十进制转十六进制
      let stri = '0'
      for (let i = 0; i < (7 - length.length); i++) {
        stri += '0'
      }
      //计算出body长度
      let len = stri + length //body的长度为39转成4位的16进制为00 00 00 26
      let cmd = '0080' //128转成两位的16进制为00 80
      //body转成16进制 十进制数据转换为16进制
      let body_16 = this.$lizhao.scale.strToHexCharCode(JSON.stringify(body))
      let hex = this.Bluetooth.agreement.magic + cmd + this.Bluetooth.agreement.id + len + body_16
      let arr = this.splitArr(hex)
      //console.log(arr);
      //多个指令串行发送，并行可能会失败
      this.writeCmd(arr, 0, '临时用印')
    },
    //结束用印
    closingSeal() {
      this.end.loading = true
      let payload = {
        id: "5927",
        method: "thing.service.authorized_over",
        params: {bizId: "", userId: this.userInfo.userId.toString()},
        "version": "1.0"
      }
      let body = {
        topic: "/sys/e2263a5940a843e3b2f4d4c90a624835/" + this.Bluetooth.device.sn + "/thing/service/authorized_over",
        payload: JSON.stringify(payload)
      }
      //console.log(body);
      let length = this.$lizhao.scale.switch_sl(JSON.stringify(body).length, 16)// 十进制转十六进制
      let stri = '0'
      for (let i = 0; i < (7 - length.length); i++) {
        stri += '0'
      }
      //计算出body长度
      let len = stri + length//body的长度为39转成4位的16进制为00 00 00 26
      let cmd = '0080'//128转成两位的16进制为00 80
      //body转成16进制 十进制数据转换为16进制
      let body_16 = this.$lizhao.scale.strToHexCharCode(JSON.stringify(body))
      let hex = this.Bluetooth.agreement.magic + cmd + this.Bluetooth.agreement.id + len + body_16
      let arr = this.splitArr(hex)
      //console.log(arr);
      //多个指令串行发送，并行可能会失败
      this.writeCmd(arr, 0, '结束用印')
    },
    //arr为hex分割的数组，i为当前数组下标
    async writeCmd(arr, i, text) {
      let res = await this.$lizhao.bluetooth.writeBLECharacteristicValue(arr[i])
      //console.log(res);
      if (res === 'writeBLECharacteristicValue:ok') {
        i++
        if (i > arr.length) {
          return
        }
        this.$lizhao.sleep.sleep(50)
        this.writeCmd(arr, i, text)
      } else {
        this.aginSendFn(text)
      }
    },
    //分割指令每20位分割一下，返回数组
    splitArr(hex) {
      let arr = []
      for (let a = 0; a < Math.ceil(hex.length / 20); a++) {
        let str = hex.slice(a * 20, a * 20 + 20)
        arr.push(str)
      }
      return arr
    },
    //重发机制
    aginSendFn(text) {
      uni.showModal({
        title: this.$t('提示'),
        content: this.$t('系统繁忙'),
        cancelText: this.$t('取消'),
        confirmText: this.$t('重新发送'),
        success: ms => {
          if (ms.confirm) {
            uni.showLoading({
              title: this.$t('重新发送') + '...',
              mask: false
            });
            if (text === '结束用印') {
              this.closingSeal()
            } else if (text === '临时用印') {
              this.setObjectModel()
            }
          }
          if (ms.cancel) {
            uni.navigateBack({
              delta: 1
            });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.temporarySeal {
  background-color: #f0f0f0;
  width: 100%;
  height: 100%;
  padding: 20rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;

  .top-text {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 200rpx;

    .num {
      font-size: 100rpx;
      font-weight: 800;
    }

    .num-text {
      font-size: 32rpx;
      color: #888;
    }
  }

  .end {
    margin-top: 100rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .e1 {
      font-size: 48rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }

    .e2 {
      color: #888;
      font-size: 28rpx;
      letter-spacing: 2rpx;

      .e-text {
        color: #007AFF;
      }
    }

    .e-icon {
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #007AFF;
      color: #fff;
      margin-top: 100rpx;
    }
  }

  .btn {
    width: 100%;
  }
}
</style>
